<template>
  <div class="statistics-container">
    <el-card class="statistics-card">
      <template #header>
        <div class="card-header">
          <h2>考勤统计分析</h2>
          <div class="header-actions">
            <el-select v-model="dateRange" placeholder="选择时间范围" @change="handleDateRangeChange">
              <el-option label="今天" value="today" />
              <el-option label="昨天" value="yesterday" />
              <el-option label="本周" value="current_week" />
              <el-option label="上周" value="last_week" />
              <el-option label="本月" value="current_month" />
              <el-option label="上月" value="last_month" />
              <el-option label="今年" value="current_year" />
              <el-option label="自定义" value="custom" />
            </el-select>
            
            <el-date-picker
              v-if="dateRange === 'custom'"
              v-model="customDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              @change="handleCustomDateChange"
            />
          </div>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="多维度工时统计" name="multidimensional-workhours">
          <multidimensional-workhours 
            :start-date="startDate" 
            :end-date="endDate" 
            :loading="loading"
            ref="multidimensionalWorkhoursRef"
          />
        </el-tab-pane>
        
        <el-tab-pane label="员工工时统计" name="employee-workhours">
          <employee-workhours 
            :start-date="startDate" 
            :end-date="endDate" 
            :loading="loading"
            ref="employeeWorkhoursRef"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

// 引入统计子组件
import MultidimensionalWorkhours from './components/MultidimensionalWorkhours.vue' // 多维度工时统计组件
import EmployeeWorkhours from './components/EmployeeWorkhours.vue' // 员工工时统计组件

// 状态变量
const loading = ref(false)          // 加载状态
const activeTab = ref('multidimensional-workhours')  // 当前激活的统计选项卡
const dateRange = ref('current_month') // 默认时间范围为本月
const customDateRange = ref<[Date, Date] | null>(null) // 自定义时间范围
const periodType = ref('monthly') // 时间段统计的周期类型

// 日期计算
const today = dayjs()
// 默认日期范围设置为本月
const startDate = ref(today.startOf('month').format('YYYY-MM-DD')) // 开始日期默认为本月第一天
const endDate = ref(today.format('YYYY-MM-DD'))   // 结束日期默认为今天

// 各个组件的引用，用于调用子组件的方法
const departmentRef = ref(null)
const timePeriodRef = ref(null)
const overtimeRef = ref(null)
const absenceRateRef = ref(null)
const anomalyRef = ref(null)
const multidimensionalWorkhoursRef = ref(null)
const employeeWorkhoursRef = ref(null)

// 处理日期范围变化，根据选择的范围设置对应的开始和结束日期
const handleDateRangeChange = () => {
  if (dateRange.value === 'custom') {
    return // 自定义时间范围由用户选择
  }
  
  let start, end
  
  switch (dateRange.value) {
    case 'today':
      start = today
      end = today
      break
    case 'yesterday':
      start = today.subtract(1, 'day')
      end = today.subtract(1, 'day')
      break
    case 'current_week':
      start = today.startOf('week')
      end = today
      break
    case 'last_week':
      start = today.subtract(1, 'week').startOf('week')
      end = today.subtract(1, 'week').endOf('week')
      break
    case 'current_month':
      start = today.startOf('month')
      end = today
      break
    case 'last_month':
      start = today.subtract(1, 'month').startOf('month')
      end = today.subtract(1, 'month').endOf('month')
      break
    case 'current_year':
      start = today.startOf('year')
      end = today
      break
    default:
      start = today.startOf('month')
      end = today.endOf('month')
  }
  
  startDate.value = start.format('YYYY-MM-DD')
  endDate.value = end.format('YYYY-MM-DD')
  
  console.log('设置日期范围:', dateRange.value, startDate.value, '至', endDate.value)
  
  refreshCurrentTab()
}

// 处理自定义日期变化，当用户选择了自定义日期范围时调用
const handleCustomDateChange = () => {
  if (customDateRange.value && customDateRange.value.length === 2) {
    startDate.value = dayjs(customDateRange.value[0]).format('YYYY-MM-DD')
    endDate.value = dayjs(customDateRange.value[1]).format('YYYY-MM-DD')
    console.log('设置自定义日期范围:', startDate.value, '至', endDate.value)
    refreshCurrentTab()
  }
}

// 处理选项卡切换，刷新当前选中的统计数据
const handleTabClick = () => {
  // 切换到员工工时统计选项卡时，无论是否已选择员工，都加载数据
  if (activeTab.value === 'employee-workhours' && employeeWorkhoursRef.value) {
    employeeWorkhoursRef.value.loadData()
    return
  }
  refreshCurrentTab()
}

// 刷新当前选项卡数据，调用对应子组件的loadData方法
const refreshCurrentTab = () => {
  console.log('刷新当前选项卡:', activeTab.value, '日期范围:', startDate.value, '至', endDate.value)
  
  const refs: Record<string, any> = {
    department: departmentRef,
    'time-period': timePeriodRef,
    overtime: overtimeRef,
    'absence-rate': absenceRateRef,
    anomaly: anomalyRef,
    'multidimensional-workhours': multidimensionalWorkhoursRef,
    'employee-workhours': employeeWorkhoursRef
  }
  
  const currentRef = refs[activeTab.value]
  if (currentRef.value && typeof currentRef.value.loadData === 'function') {
    console.log('调用子组件loadData方法')
    currentRef.value.loadData()
  } else {
    console.error('无法调用子组件loadData方法，组件可能未正确初始化')
  }
}

// 组件挂载时初始化
onMounted(() => {
  console.log('统计页面组件挂载')
  // 使用默认的本月日期范围
  handleDateRangeChange() // 初始化日期范围并加载数据
})
</script>

<style scoped>
.statistics-container {
  padding: 5px;
  height: calc(100vh - 100px);
  overflow: hidden;
}

.statistics-card {
  margin-bottom: 5px;
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
}

/* 确保标签页内容区域可滚动但不影响整体页面 */
.statistics-card :deep(.el-tabs__content) {
  overflow: hidden;
  height: calc(100vh - 200px);
}

.statistics-card :deep(.el-tab-pane) {
  height: 100%;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  min-width: 600px;   /* 可根据实际需要调整数值 */
  width: auto;
  max-width: 100%;
}

h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}
</style> 